<template>
  <div class="course-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入关键字"
        style="width: 300px; margin-right: 10px"
      ></el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="info" @click="handleReset">重置</el-button>
      <el-button type="success" @click="handleAdd" style="margin-left: auto">新增课程</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="courses" style="width: 100%">
      <el-table-column
        prop="title"
        label="视频标题"
        width="200"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="fileName"
        label="课程名称"
        width="200"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column prop="status" label="发布" width="100" header-align="center" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '已发布' : '未发布' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="coverUrls"
        label="封面图"
        width="150"
        header-align="center"
        align="center"
      >
        <template #default="scope">
          <img :src="scope.row.coverUrls" alt="Cover" style="width: 100px; height: auto" />
        </template>
      </el-table-column>
      <el-table-column
        prop="viewCount"
        label="观看数量"
        width="100"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="price"
        label="视频价格"
        width="100"
        header-align="center"
        align="center"
      >
        <template #default="scope"> {{ scope.row.price.toFixed(2) }} 元 </template>
      </el-table-column>
      <el-table-column
        prop="courseType"
        label="视频分类"
        width="150"
        header-align="center"
        align="center"
      >
        <template #default="scope">
          {{ getCourseTypeName(scope.row.courseType) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="freeTime"
        label="免费时长"
        width="90"
        header-align="center"
        align="center"
      ></el-table-column>
      <el-table-column label="视频" width="200" header-align="center" align="center">
        <template #default="scope">
          <el-button v-if="scope.row.videoId" type="success" size="small" @click="handleVideoView(scope.row)"
            >视频查看</el-button
          >
          <el-tag v-else type="danger" size="small">未上传</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createBy"
        label="创建人"
        width="150"
        header-align="center"
        align="center"
      ></el-table-column>

      <el-table-column
        prop="createTime"
        label="上传时间"
        width="180"
        header-align="center"
        align="center"
      ></el-table-column>

      <el-table-column label="操作" width="200" header-align="center" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
    </div>

    <!-- 查看抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="课程详情"
      direction="rtl"
      size="40%"
      class="course-drawer"
    >
      <div class="drawer-content">
        <el-descriptions :column="1" border class="course-info">
          <el-descriptions-item label="视频标题" class="info-item">
            <span class="info-value">{{ currentCourse.title }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="课程名称" class="info-item">
            <span class="info-value">{{ currentCourse.fileName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="视频状态" class="info-item">
            <el-tag :type="currentCourse.status === 1 ? 'success' : 'info'">
              {{ currentCourse.status === 1 ? '已发布' : '未发布' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="封面图" class="info-item">
            <el-image
              :src="currentCourse.coverUrls"
              alt="Cover"
              class="cover-image"
              :preview-src-list="[currentCourse.coverUrls]"
            />
          </el-descriptions-item>
          <el-descriptions-item label="观看数量" class="info-item">
            <span class="info-value">{{ currentCourse.viewCount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="视频价格" class="info-item">
            <span class="info-value price">{{ currentCourse.price.toFixed(2) }} 元</span>
          </el-descriptions-item>
          <el-descriptions-item label="视频分类" class="info-item">
            <span class="info-value">{{ getCourseTypeName(currentCourse.courseType) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="免费时长" class="info-item">
            <span class="info-value">{{ currentCourse.freeTime }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建人" class="info-item">
            <span class="info-value">{{ currentCourse.createBy }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="上传时间" class="info-item">
            <span class="info-value">{{ currentCourse.createTime }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <div class="description-container">
          <h4 class="description-title">视频描述</h4>
          <div class="description-content" v-html="currentCourse.description"></div>
        </div>
      </div>
    </el-drawer>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑课程' : '新增课程'"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="courseRules"
        label-width="100px"
        class="course-form"
      >
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="courseForm.title" placeholder="请输入视频标题"></el-input>
        </el-form-item>
        <!-- 自定义视频上传 -->
        <el-form-item label="视频上传" prop="videoUrl">
          <el-upload
            auto-upload="false"
            :http-request="customUploadMethod"
            accept="video/*"
            :show-file-list="false"
          >
            <el-button type="primary" :loading="loading">上传视频</el-button>
          </el-upload>
        </el-form-item>
        <!-- vid -->
        <el-form-item label="视频videoId" prop="videoId">
          <el-input v-model="courseForm.videoId" placeholder="请输入视频videoId"></el-input>
        </el-form-item>
        <!-- 课程名称 -->
        <el-form-item label="课程名称" prop="fileName">
          <el-input v-model="courseForm.fileName" placeholder="请输入课程名称"></el-input>
        </el-form-item>

        <el-form-item label="发布状态" prop="status">
          <el-switch
            v-model="courseForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="发布"
            inactive-text="未发布"
          ></el-switch>
        </el-form-item>

        <el-form-item label="封面图" prop="coverUrl">
          <custom-upload
            v-model="courseForm.coverUrl"
            :limit="1"
            display-type="picture-wall"
            list-type="picture-card"
            :file-types="[1]"
          ></custom-upload>
        </el-form-item>

        <el-form-item label="视频价格" prop="price">
          <el-input-number
            v-model="courseForm.price"
            :precision="2"
            :step="0.01"
            :min="0"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="视频分类" prop="courseType">
          <el-select v-model="courseForm.courseType" placeholder="请选择视频分类">
            <el-option
              v-for="item in courseTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.itemId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="免费时长" prop="freeTime">
          <el-input v-model="courseForm.freeTime" placeholder="请输入免费时长"></el-input>
        </el-form-item>

        <el-form-item label="视频描述" prop="description">
          <el-input
            v-model="courseForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入视频描述"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="videoDialogVisible" title="视频查看" width="80%" fullscreen>
      <ali-video v-if="videoDialogVisible" :videoObj="videoObj" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import aliVideo from '@/components/aliVideo/index.vue';
import {
  geCourseInfoList,
  deleteCourseInfo,
  createCourseInfo,
  createAndUploadVideo,
  getPlayAuth,
} from '@/api/zhaokao/course';
import { getDict } from '@/api/zhaokao/zhaokao';
import customUpload from '@/components/upload/index.vue';
const customUploadMethod = options => {
  if (!courseForm.value.title) {
    ElMessage.warning('请先填写视频标题');
    return;
  }

  console.log(options);
  const formData = new FormData();
  formData.append('file', options.file);
  formData.append('title', courseForm.value.title);
  console.log(options.file);
  loading.value = true; // 开始上传时显示loading
  createAndUploadVideo(formData)
    .then(res => {
      console.log(res);
      if (res.code === 200) {
        // courseForm.value.videoUrl = res.data.videoUrl;
        courseForm.value.videoId = res.data;
        ElMessage.success('上传成功');
      } else {
        ElMessage.error('上传失败');
      }
    })
    .finally(() => {
      loading.value = false; // 上传完成后隐藏loading
    });
};
const courseTypeList = ref([]);
const getCourseType = async () => {
  const res = await getDict('course_type');
  console.log(res);
  courseTypeList.value = res.data.cachedResultList;
};
getCourseType();

// 表格数据
const courses = ref([]);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
// 搜索关键字
const searchKeyword = ref('');

// 获取课程列表
const getCourseList = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value, // 添加关键字参数
    };
    const res = await geCourseInfoList(params);
    courses.value = res.data.records.map(item => {
      try {
        if (item.coverUrl) {
          const imageData = JSON.parse(item.coverUrl);
          item.coverUrls = imageData[0]?.downloadUri || imageData[0]?.url || '';
        } else {
          item.coverUrls = '';
        }
      } catch (error) {
        console.error('解析coverUrl失败:', error);
        item.coverUrls = '';
      }
      return item;
    });
    total.value = res.data.total;
  } catch (error) {
    ElMessage.error('获取课程列表失败');
  }
};

// 分页大小改变
const handleSizeChange = val => {
  pageSize.value = val;
  getCourseList();
};

// 当前页改变
const handleCurrentChange = val => {
  currentPage.value = val;
  getCourseList();
};

// 搜索按钮点击事件
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置为第一页
  getCourseList();
};

// 重置按钮点击事件
const handleReset = () => {
  searchKeyword.value = ''; // 清空搜索关键字
  currentPage.value = 1; // 重置为第一页
  getCourseList();
};

// 组件挂载时获取数据
onMounted(() => {
  getCourseList();
});

// 查看相关状态
const drawerVisible = ref(false);
const currentCourse = ref({});

// 查看操作
const handleView = row => {
  currentCourse.value = row;
  drawerVisible.value = true;
};

// 表单相关
const formDialogVisible = ref(false);
const isEdit = ref(false);
const courseFormRef = ref(null);
const defaultForm = {
  id: null,
  title: '',
  fileName: '',
  status: 0,
  coverUrl: '',
  price: 0,
  courseType: '',
  freeTime: '',
  description: '',
};
const courseForm = ref({ ...defaultForm });

// 表单验证规则
const courseRules = {
  title: [
    { required: true, message: '请输入视频标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  fileName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  coverUrl: [{ required: true, message: '请上传封面图', trigger: 'change' }],
  price: [{ required: true, message: '请输入视频价格', trigger: 'blur' }],
  courseType: [{ required: true, message: '请输入视频分类', trigger: 'blur' }],
  videoId: [{ required: true, message: '请输入视频videoId', trigger: 'blur' }],
};

// 新增操作
const handleAdd = () => {
  isEdit.value = false;
  courseForm.value = { ...defaultForm };
  formDialogVisible.value = true;
};

// 编辑操作
const handleEdit = row => {
  console.log(row);
  isEdit.value = true;
  courseForm.value = { ...row };
  try {
    // 只在coverUrl存在且不为空时尝试解析
    if (row.coverUrl) {
      // 确保imageUrl是JSON格式的字符串
      const parsedImages = JSON.parse(row.coverUrl);

      // 确保每个图片对象都有url属性
      const formattedImages = parsedImages.map(img => ({
        ...img,
        uid: img.uid || Date.now() + Math.random().toString(36).substr(2, 8),
        status: 'success',
        url: img.url || img.downloadUri, // 修正这里，先尝试使用url，如果没有则使用downloadUri
      }));

      courseForm.value.coverUrl = formattedImages;
      console.log('回显图片数据:', formattedImages);
    } else {
      courseForm.value.coverUrl = [];
    }
  } catch (error) {
    console.error('解析imageUrl失败:', error);
    courseForm.value.coverUrl = [];
  }
  formDialogVisible.value = true;
};

// 表单提交
const submitForm = async () => {
  if (!courseFormRef.value) return;
  if (!courseForm.value.videoId) {
    ElMessage.warning('视频未上传，请先上传视频或者输入视频videoId');
    return;
  }

  await courseFormRef.value.validate(async valid => {
    if (valid) {
      try {
        // 新增模式
        await createCourseInfo(courseForm.value);
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功');
        formDialogVisible.value = false;
        getCourseList(); // 刷新表格数据
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败');
      }
    } else {
      return false;
    }
  });
};

// 删除操作
const handleDelete = async row => {
  try {
    await ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    await deleteCourseInfo(row.id);
    ElMessage.success('删除成功');
    getCourseList(); // 删除成功后刷新表格数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 获取状态标签类型
const getStatusTagType = status => {
  switch (status) {
    case '已发布':
      return 'success';
    case '审核中':
      return 'warning';
    case '已下架':
      return 'danger';
    default:
      return 'info';
  }
};

// 获取课程类型名称
const getCourseTypeName = id => {
  const type = courseTypeList.value.find(item => item.itemId === id);
  return type ? type.name : id;
};

// 视频查看
const videoDialogVisible = ref(false);
const videoObj = ref(null);
const handleVideoView = row => {
  getPlayAuth(row.videoId).then(res => {
    console.log(res);
    if (res.code = 200) {
      videoDialogVisible.value = true;
      videoObj.value = res.data;
    } else {
      ElMessage.error('获取视频播放凭证失败,视频正在转码中...');
    }

  });
};

const loading = ref(false); // 添加loading状态变量
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.course-container {
  padding: 20px;
}

.course-drawer {
  padding: 20px;
}

.drawer-content {
  padding: 0 20px;
}

.course-info {
  margin-bottom: 20px;
}

.info-item {
  padding: 12px 0;
}

.info-value {
  font-weight: 500;
  color: #606266;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.cover-image {
  width: 150px;
  height: auto;
  border-radius: 4px;
  cursor: pointer;
}

.description-container {
  margin-top: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.description-title {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.description-content {
  line-height: 1.6;
  color: #606266;
}

.description-content ::v-deep img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 10px 0;
}

.course-form {
  margin: 20px 0;
}

.preview-image {
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
